package com.example.qu_tao.View;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.example.qu_tao.R;

public class WebViewActivity extends AppCompatActivity {
    private static final String TAG = "WebViewActivity";
    private WebView webView;
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fargment_xinwen);
        Log.d(TAG, "onCreate called");

        webView = findViewById(R.id.webview);
        initWebViewSettings();
        setupJavascriptInterface();
        setupWebViewClients();

        // 加载URL
        String url = getIntent().getStringExtra("url");
        Log.d(TAG, "Loading initial URL: " + (url != null ? url : "null"));
        if (url != null) {
            webView.loadUrl(url);
        }
    }

    private void initWebViewSettings() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
    }

    private void setupJavascriptInterface() {
        webView.addJavascriptInterface(new Object() {
            @JavascriptInterface
            public void goBack() {
                Log.d(TAG, "JS 调用 goBack()，当前线程：" + Thread.currentThread().getName());

                // 切换到主线程执行 WebView 操作
                mainHandler.post(() -> {
                    if (webView != null && webView.canGoBack()) {
                        webView.goBack();
                    } else {
                        showExitDialog();
                    }
                });
            }
            @JavascriptInterface
            public void loadContent(final String content) {
                mainHandler.post(() -> {
                    if (webView != null) {
                        webView.loadData(content, "text/html", "utf-8");
                    }
                });
            }
            @JavascriptInterface
            public void finish() {
                Log.d(TAG, "JS interface called finish()");
                WebViewActivity.this.finish();
            }

            @JavascriptInterface
            public String getNewsContent(String title) {
                Log.d(TAG, "JS interface called getNewsContent with title: " + title);
                return "这是" + title + "的新闻内容";
            }

            @JavascriptInterface
            public String getNewsImagePath(String title) {
                Log.d(TAG, "JS interface called getNewsImagePath with title: " + title);
                return "file:///android_asset/pic/default_image.jpg";
            }
        }, "myInterface");
    }

    private void setupWebViewClients() {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                // 关键：拦截 URL 并手动加载，让 WebView 记录历史
                view.loadUrl(request.getUrl().toString());
                return true; // 返回 true 表示已处理跳转，WebView 会记录历史
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d(TAG, "Page finished: " + url);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d(TAG, "JS Console: " + consoleMessage.message() +
                        " (Line: " + consoleMessage.lineNumber() + ")");
                return super.onConsoleMessage(consoleMessage);
            }
        });
    }

    private void showExitDialog() {
        // 主线程中创建对话框
        finish();
    }

    @Override
    public void onBackPressed() {

        Log.d(TAG, "onBackPressed，当前线程：" + Thread.currentThread().getName());
        if (webView != null && webView.canGoBack()) {
            webView.goBack();
        } else {
            showExitDialog();
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy called");
        if (webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }
}